<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form">
                <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">配送单编号：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="deliveryOrderCode" type="text" class="layui-input" placeholder="配送单编号">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">所属配货需求订单：</label>
                                    <div class="layui-input-inline mr0">
                                        <input  name="distCode" type="text" class="layui-input" placeholder="所属配货需求订单">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">创建时间：</label>
                                    <div class="layui-input-inline">
                                        <input  id="pTime" class="layui-input date-icon" type="text" placeholder="选择创建时间" autocomplete="off" readonly/>
                                        <input name="startCreateTime" id="sTime" style="display: none"/>
                                        <input name="endCreateTime" id="eTime" style="display: none"/>
                                    </div>

                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn" lay-filter="formSubSearchLog" lay-submit
                                            type="button">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit
                                            type="reset">
                                        重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            </form>
            <!-- 表格 -->
            <table class="layui-table" id="orderDeliveryTable" lay-filter="orderDeliveryTable"></table>
        </div>
    </div>
</div>

<style>
    .open-details-title {
        width: 100%;
        height: 40px;
        padding: 0 20px;
        font-size: 15px;
        font-weight: 500;
        background: #F9FAFE;
        position: relative;
        display: flex;
        align-items: center;
        box-sizing: border-box;
    }

    .open-details-title:before {
        content: "";
        display: inline-block;
        width: 4px;
        height: 16px;
        background: #009C5E;
        margin-right: 10px;
    }

    .layui-table-cell {
        height: auto;
        max-height: 80px;
    }
</style>
<!-- 表格操作列 -->
<script type="text/html" id="orderDeliveryTableBar">
    <a class="layui-btn layui-btn-xs" lay-event="details">详情</a>

    {{# if(d.status != "sign"){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">签收</a>
    {{# }else{ }}

    {{# } }}

</script>

<!-- 详情弹窗 -->
<script type="text/html" id="orderDeliveryForm">
    <div class="layui-card-body">
        <div class="layui-form-item">
            <table class="layui-table" id="orderDeliveryFormTable" lay-filter="orderDeliveryFormTable"></table>
        </div>
        <div class="open-details-title" style="margin-top: 40px">配送物资信息：</div>
        <div class="layui-form-item">
            <table class="layui-table" id="orderDeliveryFormTableList" lay-filter="orderDeliveryFormTableList"></table>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label w-auto">制单人:</label>
            <div class="layui-form-mid layui-word-aux">
                <span id="preparer"></span>
            </div>
        </div>
    </div>
</script>

<!-- 签收弹窗 -->
<script type="text/html" id="cloudStorageSignModelForm">
    <form lay-filter="cloudStorageSignModelForm" class="layui-form model-form" onsubmit="return false;">
        <div class="open-details-box">
            <div class="layui-row">
                <table class="layui-table" id="signShowDetailTable" lay-filter="signShowDetailTable"></table>
            </div>
            <div class="layui-row" style="margin-top: 15px;">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <div class="open-details-title">签收订单信息</div>
                    </div>
                    <table class="layui-table" id="signInfoDetailTable" lay-filter="signInfoDetailTable"></table>
                </div>
                <div class="layui-col-md8" style="padding-left: 25px">
                    <div class="layui-form-item">
                        <div class="open-details-title">签收物资</div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label w-auto">扫描包装条码</label>
                        <div class="layui-input-inline" style="width: 260px;">
                            <input name="scanningCode" type="text" class="layui-input" id="scanningCode"/>
                        </div>
                        <div class="layui-input-inline">
                            <a class="layui-btn icon-btn color-green" id="scanningBtn" type="button">确定</a>
                        </div>
                    </div>
                    <table class="layui-table" id="signInGoodsTable" lay-filter="signInGoodsTable"></table>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="cloudStorageSignFormSubmit" lay-submit type="button">保存</button>
        </div>
    </form>
</script>

<!--签收表格操作列-->
<script type="text/html" id="signInfoDetailTableBar">
    <!--    //created receive  creation-->
    {{# if(d.status=="creation"){  }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="sign">签收</a>
    {{# }else if(d.status =="sign"){ }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    {{# } }}
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;

        //日期范围
        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function(value, date, endDate){
                if (value){
                    let dateValue = value.split(" - ");
                    $("input[name='startCreateTime']").val(dateValue[0] + " 00:00:00");
                    $("input[name='endCreateTime']").val(dateValue[1] + " 23:59:59");
                }else {
                    $("input[name='startCreateTime']").val("");
                    $("input[name='endCreateTime']").val("");
                }
            }
        });

        // 渲染表格
        var insTb = table.render({
            elem: '#orderDeliveryTable',
            url: config.base + "enterprisecab/order/admin/orderDelivery/getOrderDeliveryVOList",
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号'}
                , {field: 'deliveryOrderCode', sort: true, title: '配送单编号'}
                , {field: 'distCode',title: '所属配货需求订单'}
                , {field: 'quantityDistribute',title: '配货数量'}
                , {field: 'distributionValue',title: '配货价值'}
                , {field: 'distributionClerk', title: '配货员'}
                , {field: 'distributionClerkPhone',title: '配货员电话'}
                , {field: 'createTime', sort: true, title: '配送出发时间'}//createTime
                , {field: 'statusDesc', title: '状态'}   //,templet: (d)=> d.status == 'created'?'已创建':'待认领'
                , {align: 'left', toolbar: '#orderDeliveryTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {

            }
        });

        //渲染下拉框
        form.render('select');

        // 工具条点击事件
        table.on('tool(orderDeliveryTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'details') { //详情
                showDetailsModel(data);
            } else if (obj.event === 'del') { // 删除
                showSignForModel(data)
            }
        });

        //监听排序
        table.on('sort(orderDeliveryTable)', function (obj) {
            table.reload('orderDeliveryTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });


        // 显示详情弹窗
        function showDetailsModel(data) {
            admin.open({
                type: 1,
                area: '1540px',
                offset: '65px',
                // isDetail:true,
                title: '详情',
                content: $('#orderDeliveryForm').html(),
                success: function () {
                    //制单人
                    $("#preparer").text(data.creatorName);

                    // 渲染表格
                    var orderDeliveryFormTb = table.render({
                        elem: '#orderDeliveryFormTable',
                        data: [data],
                        cols: [[
                            {field: 'deliveryOrderCode', title: '配送单编号',}
                            , {field: 'distCode', title: '所属配货需求订单'}
                            , {field: 'enterpriseName', title: '所属企业'}
                            , {field: 'quantityDistribute', title: '配货数量'}
                            , {field: 'distributionValue', title: '配货价值'}
                            , {field: 'distributionClerk', title: '配货员'}
                            , {field: 'distributionClerkPhone', title: '配货员电话'}
                            , {field: 'preparationTime', title: '制单时间'}
                            , {field: 'departureTime', title: '出发时间'}
                        ]]
                    });

                    var orderDeliveryFormTbList = table.render({
                        elem: '#orderDeliveryFormTableList',
                        url: config.base + 'enterprisecab/order/admin/orderDelivery/getOrderDeliveryDetailVOList?deliveryId=' + data.id,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', title: '序号'}
                            , {field: 'typeName', title: '类型'}
                            , {field: 'skuCode', title: '平台物料编号'}
                            , {field: 'picture', title: '图片', templet: (d) => "<img src='" + d.picture + "'/>"}
                            , {field: 'skuName', title: '物料名称'}
                            , {field: 'skuSpecValueNames', title: '规格'}
                            , {field: 'enterpriceCode', title: '企业货号'}
                            , {
                                field: 'marketPrice',
                                title: '单价',
                                templet: (d) => "<span style='color: red'>" + d.price + "</span>"
                            }
                            , {field: 'planReplenishment', title: '需求数'}//quantityConfirm
                            , {
                                field: 'quantityReceive',
                                title: '配送数量',
                                templet: (d) => "<span style='color: red'>" + d.quantityReceive + "</span>"
                            }
                            , {field: 'unitName', title: '单位'}
                            , {
                                field: 'totalPrice',
                                title: '总价',
                                templet: (d) => "<span style='color: red'>" + d.totalPrice + "</span>"
                            }
                        ]]
                    });

                }
            });
        }

        // 显示签收弹窗
        function showSignForModel(data) {
            admin.open({
                type: 1,
                area: '1560px',
                offset: '65px',
                title: '签收任务详情',
                content: $('#cloudStorageSignModelForm').html(),
                success: function () {
                    var insTb2 = table.render({
                        elem: '#signShowDetailTable',
                        data: [data],
                        cellMinWidth: 120,
                        cols: [[
                            // {field: '', title: '签收记录编号', align: 'center'}
                            {field: 'deliveryOrderCode', title: '配送任务编号', align: 'center'}
                            , {field: 'distCode', title: '所属配货订单', align: 'center'}
                            // ,{field: 'quantity', title: '补货需求订单', align: 'center'}
                            , {field: 'skuNum', title: '配送物料数', align: 'center'}
                            , {field: 'cabNum', title: '柜子数', align: 'center'}
                            , {field: 'statusDesc', title: '状态', align: 'center'}
                            , {field: 'distributionClerk', title: '配送员', align: 'center'}
                            , {field: 'signer', title: '签收人', align: 'center'}
                        ]]
                    });

                    let scanningData = [];
                    let jobProductId = '';

                    var insTb3 = table.render({
                        elem: '#signInfoDetailTable',
                        url: config.base + 'enterprisecab/order/admin/orderDelivery/getOrderDeliveryDetailVOList?deliveryId=' + data.id,
                        cellMinWidth: 100,
                        cols: [[
                            {title: '序号', width: 50, type: 'numbers'}
                            , {field: 'skuCode', title: '物料编号', align: 'center'}
                            , {field: 'productName', title: '物料名称', align: 'center'}
                            , {field: 'quantityReceive', title: '应收数', align: 'center'}
                            , {field: 'realReceive', title: '已签收数', align: 'center'}
                        ]]
                    });

                    table.on('row(signInfoDetailTable)', function (obj) {
                        jobProductId = obj.data.id;
                        admin.req("enterprisecab/order/admin/orderDelivery/getProductPackLabelSign", {"deliveryDetailId": jobProductId}, (res) => {
                            if (res.code == "200") {
                                res.data.forEach((item, index) => {
                                    let scanningType = scanningData.find(ev => ev.id == item.id) ? true : false;
                                    if (scanningType) {
                                        return false;
                                    }
                                    item.status = 'fulfill';
                                    scanningData.push(item);
                                    layer.msg(res.msg, {icon: 1});
                                    table.reload('signInGoodsTable', {data: scanningData});
                                })

                            } else {
                                scanningData = [];
                                table.reload('signInGoodsTable', {data: scanningData});
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'GET');
                    });


                    var insTb4 = table.render({
                        elem: '#signInGoodsTable',
                        data: scanningData,
                        // url: config.base + 'enterprisecab/order/admin/orderDelivery/getOrderDeliveryDetailVOList?deliveryId='+data.id,
                        cellMinWidth: 120,
                        cols: [[
                            {title: '序号', type: 'numbers'}
                            , {field: 'packLabelCode', title: '包装码', align: 'center'}
                            , {field: 'skuCode', title: '物料编号', align: 'center'}
                            , {field: 'packName', title: '包装规格', align: 'center'}
                            , {field: 'packLabelQuantity', title: '配送数(按最小单位)', align: 'center'}
                            , {
                                field: 'realReceive', title: '签收数(按最小单位)', templet: function (d) {
                                    d.realReceive = d.realReceive == 0 ? d.packLabelQuantity : d.realReceive;
                                    if (d.status == 'sign' || d.status == 'fulfill') {
                                        return '<span>' + d.realReceive + '</span>'
                                    } else {
                                        return '<input signId="' + d.id + '" class="layui-input realReceive" style="height: 28px;" type="text" ' +
                                            'value="' + d.realReceive + '" />'
                                    }
                                }
                            }
                            , {
                                field: 'abnormalQuantity', title: '异常数(按最小单位)', templet: function (d) {
                                    if (d.status == 'sign' || d.status == 'fulfill') {
                                        return '<span>' + d.abnormalQuantity + '</span>'
                                    } else {
                                        return '<input signId="' + d.id + '" class="layui-input abnormalQuantity" style="height: 28px;" type="text" ' +
                                            'value="' + d.abnormalQuantity + '" />'
                                    }
                                }
                            }
                            , {field: 'statusDesc', title: '状态', align: 'center', width: '100'}
                            , {align: 'center', toolbar: '#signInfoDetailTableBar', title: '操作'}
                        ]],

                    });

                    $("#scanningBtn").click((_data) => {
                        if ($("#scanningCode").val().length == 0) {
                            layer.msg("包装条码不能为空", {icon: 7});
                            return false;
                        }
                        $("#scanningCode").val($.trim($("#scanningCode").val()));
                        admin.req("enterprisecab/order/admin/orderDelivery/getOrderDistributionLabelVOByCode", {
                            "deliveryId": data.id,
                            "packLabelCode": $("#scanningCode").val()
                        }, (res) => {
                            if (res.code == "200") {
                                let scanningType = scanningData.find(ev => ev.id == res.data.id) ? true : false
                                if (scanningType) {
                                    return false
                                }
                                scanningData.push(res.data);
                                table.reload('signInGoodsTable', {data: scanningData});
                                layer.msg(res.msg, {icon: 1});
                            } else {
                                layer.msg(res.msg, {icon: 5});
                            }
                        }, 'GET');
                    });

                    // 监听签收数
                    $("body").delegate(".realReceive", "change", function () {
                        let id = $(this).attr('signId');
                        let packLabeQuantity = Math.abs(parseInt($(this).val().replace(/[^0-9]/g, ''))) || 0;
                        scanningData.forEach((item, index) => {
                            if ((item.id === id)) {
                                let quantity = Math.abs(parseInt(item.packLabelQuantity));
                                if (packLabeQuantity > quantity) {
                                    layer.msg('签收数量不能大于应收数量', {icon: 2});
                                    $(this).val(quantity);
                                    $(this).parents('td').siblings().find('.abnormalQuantity').val(0);
                                    return false;
                                }
                                let abnormalQuantity = quantity - packLabeQuantity;
                                $(this).val(packLabeQuantity);
                                $(this).parents('td').siblings().find('.abnormalQuantity').val(abnormalQuantity);
                            }
                        })
                    });

                    // 监听异常数量
                    $("body").delegate(".abnormalQuantity", "change", function () {
                        let id = $(this).attr('signId');
                        let abnormalQuantity = Math.abs(parseInt($(this).val().replace(/[^0-9]/g, ''))) || 0;
                        scanningData.forEach((item, index) => {
                            if ((item.id === id)) {
                                let quantity = Math.abs(parseInt(item.packLabelQuantity));
                                if (abnormalQuantity > quantity) {
                                    layer.msg('异常数量不能大于应收数量', {icon: 2});
                                    $(this).val(quantity);
                                    $(this).parents('td').siblings().find('.realReceive').val(0);
                                    return false;
                                }
                                let packLabeQuantity = quantity - abnormalQuantity;
                                $(this).val(abnormalQuantity);
                                $(this).parents('td').siblings().find('.realReceive').val(packLabeQuantity);
                            }
                        })
                    });

                    // 工具条点击事件
                    table.on('tool(signInGoodsTable)', function (obj) {
                        var data = obj.data;
                        if (obj.event === 'sign') { // 签收
                            let packLabeQuantity = $(this).parents('td').siblings().find('.realReceive').val(); //签收数
                            let abnormalQuantity = $(this).parents('td').siblings().find('.abnormalQuantity').val(); //异常数
                            scanningData.forEach((item, index) => {
                                if ((data.id === item.id)) {
                                    if (packLabeQuantity <= 0) {
                                        layer.msg('签收数不能小于0', {'icon': 2});
                                        return;
                                    }
                                    scanningData[index].realReceive = packLabeQuantity;
                                    scanningData[index].abnormalQuantity = abnormalQuantity;
                                    scanningData[index].status = 'sign';
                                    scanningData[index].statusDesc = '已签收';
                                }
                            });
                        } else if (obj.event === 'edit') { //修改
                            scanningData.forEach((item, index) => {
                                if ((data.id === item.id)) {
                                    scanningData[index].status = 'creation';
                                }
                            });
                        }
                        table.reload('signInGoodsTable', {data: scanningData});
                    });

                    form.on('submit(cloudStorageSignFormSubmit)', function (d) {
                        if (scanningData.length == 0) {
                            layer.msg('包装条码不能为空', {icon: 2});
                            return false;
                        }
                        let paramData = [];
                        scanningData.forEach((item, index) => {
                            if ((item.status != 'fulfill')) {
                                if (item.status != 'creation') {
                                    paramData.push(item)
                                }
                            }
                        });
                        if (paramData.length == 0) {
                            layer.msg('请先签收物资', {icon: 2});
                            return false;
                        }
                        layer.load(2);
                        admin.req('enterprisecab/order/admin/orderDelivery/deliverySign', JSON.stringify(paramData), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                // 清空签收数据
                                scanningData = [];
                                table.reload('signInGoodsTable', {data: scanningData});
                                table.reload('orderDeliveryTable')
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });


                }
            });
        }


        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/order/admin/orderDelivery/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }
    });
</script>